﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Common.Logging;
using WuDada.Core.SystemApplications;
using WuDada.Trade.DataLoader.Service;
using WuDada.Core.SystemApplications.Service;
using WuDada.Core.SystemApplications.Domain;
using WuDada.Trade.DataLoader.Domain;
using System.Net;
using System.Text;
using WuDada.Trade.DataLoader.Utility;
using System.IO;
using CsQuery;

public partial class Manage_googleStockList : System.Web.UI.Page
{
    private ILog m_Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    private TradeDataLoaderFactory m_TradeDataLoaderFactory = new TradeDataLoaderFactory();
    private SystemFactory m_SystemFactory = new SystemFactory();
    private IDataLoadService m_DataLoadService;
    private ISystemService m_SystemService;
    private string m_ItemClassify = "YahooStock";
    //private int m_PageNum = 200;
    //private int m_dataSize = 4000;
    protected string m_Period;
    private ConfigHelper configHelper = new ConfigHelper();

    //protected string pingTarget;
    protected string period = "Day";
    //protected int pageNum;

    protected void Page_Load(object sender, EventArgs e)
    {
        m_DataLoadService = m_TradeDataLoaderFactory.GetDataLoadService();
        m_SystemService = m_SystemFactory.GetSystemService();

        if (!IsPostBack)
        {
            SetControl();
            LoadDataToUI();
        }
    }

    private void SetControl()
    {
        //年
        ddlStartYear.Items.Clear();
        ddlEndYear.Items.Clear();
        for (int i = DateTime.Today.Year; i >= 1990; i--)
        {
            ddlStartYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
            ddlEndYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
        }

        //日
        ddlStartDay.Items.Clear();
        ddlEndDay.Items.Clear();
        for (int i = 1; i <= 31; i++)
        {
            ddlStartDay.Items.Add(new ListItem(i.ToString(), i.ToString()));
            ddlEndDay.Items.Add(new ListItem(i.ToString(), i.ToString()));
        }

        //初始
        string month = (DateTime.Today.Month - 1).ToString().PadLeft(2, '0');
        ddlStartYear.SelectedValue = DateTime.Today.Year.ToString();
        ddlEndYear.SelectedValue = DateTime.Today.Year.ToString();
        m_Log.Debug("month = " + month);
        ddlStartMonth.SelectedValue = month;
        ddlEndMonth.SelectedValue = month;
        ddlStartDay.SelectedValue = DateTime.Today.Day.ToString();
        ddlEndDay.SelectedValue = DateTime.Today.Day.ToString();
    }

    private void LoadDataToUI()
    {
        //pingTarget = configHelper.GetStockData_Google_URL;
        period = StockDataVO.StockDataPeriod.Day.ToString();
        //pageNum = 200;
        GetStockList();
    }

    private void GetStockList()
    {
        gvList.DataSource = m_SystemService.GetAllItemParamByNoDel(m_ItemClassify);
        gvList.DataBind();
    }

    protected void btnDownLoadAll_Click(object sender, EventArgs e)
    {
        IList<ItemParamVO> stockList = m_SystemService.GetAllItemParamByNoDel(m_ItemClassify);

        if (stockList != null && stockList.Count > 0)
        {
            foreach (ItemParamVO stock in stockList)
            {
                DoGetGoogleStockDataByRule(stock);
            }
        }
    }

    private void DoGetGoogleStockDataByRule(ItemParamVO stock)
    {
        DoGetYahooStockData(stock);
    }

    private void DoGetYahooStockData(ItemParamVO stock)
    {
        //"http://ichart.finance.yahoo.com/table.csv?s=4103.TWO&a=00&b=1&c=2000&d=08&e=3&f=2012&g=d&ignore=.csv";
        string url = string.Format("http://ichart.finance.yahoo.com/table.csv?s={0}&a={1}&b={2}&c={3}&d={4}&e={5}&f={6}&g=d&ignore=.csv"
            , stock.Value, ddlStartMonth.SelectedValue, ddlStartDay.SelectedValue, ddlStartYear.SelectedValue
            , ddlEndMonth.SelectedValue, ddlEndDay.SelectedValue, ddlEndYear.SelectedValue);

        string result = Get(url);
        //m_Log.Debug(result);

        string[] rows = result.Replace("\r", "").Split('\n');

        for (int i = 0; i < rows.Count(); i++)
        {
            //第一行為標題要跳過
            if (i == 0)
            {
                continue;
            }

            string row = rows[i];
            if (!string.IsNullOrEmpty(row))
            {
                //m_Log.Debug("row = " + row);
                string[] cols = row.Split(',');

                string date = cols[0];
                double open = double.Parse(cols[1]);
                double high = double.Parse(cols[2]);
                double low = double.Parse(cols[3]);
                double close = double.Parse(cols[4]);
                string volume = cols[5];

                CreateStockData(stock.Value, date, open, high, low, close, volume);
            }
        }
    }

    private void CreateStockData(string stockCode, string strDataTime, double openValue
        , double highValue, double lowValue, double closeValue, string strVolume)
    {
        try
        {
            int volume = int.Parse(strVolume);
            DateTime dataTime = DateTime.Parse(strDataTime);

            //先判斷該筆資料是否有建立過
            if (m_DataLoadService.GetStockData(stockCode, dataTime) != null)
            {
                m_Log.Debug(string.Format("{0} exist.", stockCode));
            }
            else
            {
                StockDataVO stockDataVO = new StockDataVO();
                stockDataVO.StockCode = stockCode;
                stockDataVO.Period = (StockDataVO.StockDataPeriod)Enum.Parse(typeof(StockDataVO.StockDataPeriod), period);
                stockDataVO.DataTime = dataTime;
                stockDataVO.OpenValue = openValue;
                stockDataVO.HighValue = highValue;
                stockDataVO.LowValue = lowValue;
                stockDataVO.CloseValue = closeValue;
                stockDataVO.Volume = volume;

                stockDataVO = m_DataLoadService.CreateStockData(stockDataVO);

                m_Log.Debug(string.Format("{0} ok.", stockCode));
            }


        }
        catch (Exception ex)
        {
            m_Log.Error(ex);
        }
    }

    private string Get(string url)
    {
        m_Log.Debug("url = " + url);
        WebClient c = new WebClient();
        //byte[] response = c.DownloadData(url);
        //return Encoding.UTF8.GetString(response);
        return c.DownloadString(url);
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        string name = txtName.Text.Trim();
        string value = txtStockCode.Text.Trim() + ddlCode.SelectedValue;
        ItemParamVO itemParamVO = new ItemParamVO(m_ItemClassify, name, value, false);
        m_SystemService.CreateItemParam(itemParamVO);
        ClearUI();
        GetStockList();
    }

    private void ClearUI()
    {
        txtName.Text = string.Empty;
        txtStockCode.Text = string.Empty;
    }

    protected void gvList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        string cmdName = e.CommandName;
        int itemParamId = int.Parse(e.CommandArgument.ToString());
        ItemParamVO itemParamVO = m_SystemService.GetItemParamById(itemParamId);
        switch (cmdName)
        {
            case "myDel":
                m_SystemService.DeleteItemParam(itemParamVO);
                break;
            case "myGetData":
                DoGetGoogleStockDataByRule(itemParamVO);
                break;
            case "myGenFile":
                GenFile(itemParamVO);
                break;
            default:
                break;
        }
        GetStockList();
    }

    private void GenFile(ItemParamVO itemParamVO)
    {
        IList<StockDataVO> dataList = m_DataLoadService.GetStockDataList(
            itemParamVO.Value, StockDataVO.StockDataPeriod.Day, null, null, "DataTime", false);

        if (dataList != null & dataList.Count > 0)
        {
            string fileName = itemParamVO.Value.Replace(".", "");
            string outputPath = Server.MapPath("../Data/");

            FileStream fs = File.Create(Path.Combine(outputPath, fileName + ".csv"));
            fs.Close();
            fs.Dispose();

            StreamWriter stmWtr = new StreamWriter(Path.Combine(outputPath, fileName + ".csv"), true);

            foreach (StockDataVO stockData in dataList)
            {
                //寫入檔案到.csv
                stmWtr.WriteLine(ToCSVObject(stockData));
            }

            stmWtr.Close();
            stmWtr.Dispose();
        }
    }

    public static string ToCSVObject(StockDataVO stockDataVO)
    {
        string result = string.Format("{0},{1},{2},{3},{4},{5}"
            , stockDataVO.DataTime.ToString("yyyy/MM/dd"), stockDataVO.OpenValue, stockDataVO.HighValue
            , stockDataVO.LowValue, stockDataVO.CloseValue, stockDataVO.Volume);
        return result;
    }

    protected void gvList_RowDataBound(object sender, GridViewRowEventArgs e)
    {

    }

    protected void btnGenFileAll_Click(object sender, EventArgs e)
    {
        IList<ItemParamVO> stockList = m_SystemService.GetAllItemParamByNoDel(m_ItemClassify);

        if (stockList != null && stockList.Count > 0)
        {
            foreach (ItemParamVO stock in stockList)
            {
                GenFile(stock);
            }
        }
    }
}